package com.liuwa.crontab;

import com.liuwa.common.utils.LockUtils;
import com.liuwa.framework.web.service.FileService;
import com.liuwa.framework.web.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
@Lazy(false)
@Async
public class Crontab {

    private static final Logger logger = LoggerFactory.getLogger(Crontab.class);

    @Autowired
    private FileService fileService;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenService tokenService;




    /**
     * 每分钟心跳
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void redisHeartBeat(){
        String lockKey = "crontab:redis:heartbeat";
        if(LockUtils.lock(lockKey)){
            try{
                redisTemplate.execute((RedisCallback<String>) connection -> {
                    // 使用 Lettuce RedisConnection 来执行 PING 命令
                    String pong = connection.ping();
                    if(!"PONG".equals(pong)){
                        logger.error("{} {}", pong, "Redis is not reachable");
                    }
                    return "PONG".equals(pong) ? "Redis is reachable" : "Redis is not reachable";
                });
            }
            catch (Exception ex){
                logger.error(ex.getMessage(), ex);
            }
            finally {
                LockUtils.unlock(lockKey);
            }
        }
    }

    /**
     * 每10分钟更新token 映射
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void refreshTokenMapping(){
        String lockKey = "crontab:token:mapping";
        if(LockUtils.lock(lockKey)){
            try{
                tokenService.refreshTokenMappings();
            }
            catch (Exception ex){
                logger.error(ex.getMessage(), ex);
            }
            finally {
                LockUtils.unlock(lockKey);
            }
        }

    }

    /**
     * 清理临时文件 （每小时）
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void clearTempFile(){
        String lockKey = "crontab:clear:tempFile";
        if(LockUtils.lock(lockKey)){
            try{
                fileService.clearTemp();

                fileService.clearDownload();
            }
            catch (Exception ex){
                logger.error(ex.getMessage(), ex);
            }
            finally {
                LockUtils.unlock(lockKey);
            }
        }
    }



}